/*
 *  $TEAM_NAME Space Trader
 */
package views;

import models.Player;
import models.TradeGood;
import presenters.TradeGoodPresenter;

import javax.swing.JPanel;

import java.awt.Dimension;

import java.util.ArrayList;
import java.util.List;

/**
 * Trade Good Table for marketplace
 * @author twb
 * @version 1.0
 */
public class TradeGoodTablePanel extends JPanel {
	
	/**
	 * Forty
	 */
	private static final int FORTY = 40;
	
	/**
	 * field
	 */
	private final Player player;
	
	/**
	 * field
	 */
	private final int planetTech;
	
	/**
	 * field
	 */
	private final List<TradeGoodPanel> tradeGoodViews;
	
	/**
	 * Constructor of TradeGoodTablePanel
	 * 
	 * @param player The player of the game
	 */
    public TradeGoodTablePanel(Player player) {
        super.setLayout(null);

        tradeGoodViews = new ArrayList<TradeGoodPanel>();
        
        planetTech = player.getLocation().getTechLevel().ordinal();
        
        for (TradeGood good : TradeGood.getTradeGoods()) {
    		TradeGoodPanel view = new TradeGoodPanel(player, good);
    		TradeGoodPresenter tradeGoodPresenter = new TradeGoodPresenter(player, view);
    		super.add(view);
    		tradeGoodViews.add(view);
        }
        
        this.player = player;
    }

    /**
     * Updates the TradeGoodPanel
     */
    public void update() {
        for (TradeGoodPanel view : tradeGoodViews) {
        	TradeGood good = view.getTradeGood();
        	//int planetTech = player.getLocation().getTechLevel().ordinal();
        	 
        	if (good.getMTLP() <= planetTech) {
        		view.getBuyButton().setEnabled(true);
        	} else {
        		view.getBuyButton().setEnabled(false);
        	}
        	
        	if (good.getMTLU() <= planetTech) {
        		view.getSellButton().setEnabled(true);
        	} else {
        		view.getSellButton().setEnabled(false);
        	}
        	
            view.update();
        }
    }

    /**
     * Lays out the subviews
     */
    public void layoutSubviews() {
        final Dimension size = getSize();

        int y = 0;
        for (TradeGoodPanel view : tradeGoodViews) {
        	
            view.setBounds(0, y, size.width, FORTY);
            y += FORTY;
        }
        
    }

    /**
     * Sets the bounds of the trade good panel
     * 
     * @param x x Position
     * @param y y Position
     * @param width The width
     * @param height The height
     */
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        layoutSubviews();
    }

    /**
     * Gets the number of trade good rows
     * 
     * @return the number of trade good rows
     */
    public int getNumTradeGoods(){
    	return tradeGoodViews.size();
    }
}
